<!DOCTYPE html>
<html lang="zh-CN">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.ico">
  <link rel="icon" type="image/png" href="/img/favorite.ico">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="小九的日常笔记">
  <meta name="author" content="小九">
  <meta name="keywords" content="笔记，博客，前端，html，css，javascript，面试题，前端面试题">
  <title>实现网站流量统计(前端埋点) - 小九的书柜</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/github-gist.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->

  
<link rel="stylesheet" href="/css/my.css">



<!-- 
<link rel="stylesheet" href="/css/message.css">
 -->
<!-- 
<link rel="stylesheet" href="https://at.alicdn.com/t/font_1117508_wxidm5ry7od.css">
 -->

  <script  src="/js/utils.js" ></script>
<meta name="generator" content="Hexo 4.2.1"></head>



<body>
  
  <div id="background">
    <!--  -->
    <header style="height: 70vh;">
      <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
      href="/">&nbsp;<strong>jLongYan's blog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
      data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
      aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/">
            <i class="iconfont icon-home-fill"></i>
            首页
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/archives/">
            <i class="iconfont icon-archive-fill"></i>
            归档
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/categories/">
            <i class="iconfont icon-category-fill"></i>
            分类
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/tags/">
            <i class="iconfont icon-tags-fill"></i>
            标签
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/links/">
            <i class="iconfont icon-link-fill"></i>
            友链
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/about/">
            <i class="iconfont icon-user-fill"></i>
            关于
          </a>
        </li>
        
        
        
        <li class="nav-item" onclick="switchDarkMode()">
          <span id="dark"></span>
        </li>
        
      </ul>
    </div>
  </div>
</nav>
<style>
  .active {
    /* border-bottom: 1px solid #00FFFF; */
    color: #00FFFF !important;
  }
</style>

<script>
  var isNight = new Date().getHours() >= 22 || new Date().getHours() < 5; // 指定时间
  // 依次判断 系统暗黑模式 指定时间 缓存 dark
  if (matchMedia('(prefers-color-scheme: dark)').matches || isNight || localStorage.getItem('dark') === '1') {
    if (!(isNight && localStorage.getItem('noDark') === '1')) {
      document.body.classList.add('dark');
    }
  }
  //点击事件
  function switchDarkMode() {
    if ($('body').hasClass('dark')) {
      // checkWallaper()
      document.getElementById('dark').style.backgroundImage = 'url(/img/太阳.png)'
      document.body.classList.remove('dark');
      localStorage.setItem('noDark', '1');
      localStorage.setItem('dark', '0');
    } else {
      document.getElementById('dark').style.backgroundImage = 'url(/img/月亮.png)'
      document.body.classList.add('dark');
      localStorage.setItem('dark', '1');
      localStorage.setItem('noDark', '0');
      // checkWallaper()
    }
  }

</script>



      <!-- 如果需要采用配置文件的路径 在下面的div粘贴此段代码进去即可 目前采用的是 自定义的随机图片 -->
      <!-- style="background: url('/img/default.png') no-repeat center center;background-size: cover;" -->
      <div class="view intro-2" id="indexBackground" parallax=true
        style='background-size:cover'>
        <div class="full-bg-img">
          <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.1)">
            <div class="container text-center white-text fadeInUp">

              <span class="h2" id="subtitle">
                
              </span>

              <div id="yiyan" onclick="watchYiyan()">只有极其努力，才能看起来毫不费力。</div>

              


              
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-06-25 19:26">
      2019年6月25日 晚上
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.2k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      26
       分钟
    </span>
  

  
  
    
  
</div>
<!-- <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script> -->
              
            </div>

            
            <div class="scroll-down-bar">
              <i class="iconfont icon-arrowdown"></i>
            </div>
            
          </div>
        </div>
      </div>
    </header>
    <!--  -->



    <main>
      
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
              <p class="note note-info">
                
                  本文最后更新于：2020年8月5日 上午
                
              </p>
            
            <article class="markdown-body">
              <p>实现网站流量统计(前端埋点)</p>
<hr>
<p>通常对于网站流量统计在目前而言会有许多第三方的插件，或者统计工具，对于自己的博客，之前用的第三方的插件，但是免费的接口速度不是很快，也会偶尔出现异常问题。</p>
<h4 id="优点"><a href="#优点" class="headerlink" title="优点"></a>优点</h4><ul>
<li>所以想要自己实现这样的一个功能，第一个自己写的速度肯定更快，不会出现偶尔网络问题不能访问，自己也可以了解下前端埋点的大概流程</li>
<li>第二对于这种插件，经常会遇到的一个问题就是如果自己更换了域名就会出现，一切从0开始的情况，好不容易积累的数字变成0自然是不开心，虽然可能他的作用不是很大，但是毕竟是自己的劳动成果，所以自己写就不会出现这个问题了。</li>
</ul>
<h4 id="思路"><a href="#思路" class="headerlink" title="思路"></a>思路</h4><ul>
<li><p>前端埋点的方法多种多样，而我需求所需要的就目前而言并不复杂，只需要知道网站的pv:访问量和uv:访问人数，针对于pv在客户端的计算机制一般是以一刷新页面或者跳转页面为1，所以要想触发uv非常简单，然后需要了解uv的计算了，uv是指访问人数，一个人会产生多次pv但是uv一个人只能是1，24小时一个人纪为1，所以如何辨别uv是需要了解的，uv的识别方法很多种：</p>
<blockquote>
<p>通常来讲我们可以通过客户端ip来区分，也就是说一个ip就是一个uv一个新用户，当网页被访问时，拿到ip，并且把ip存入数据库，在这里可以用到Redis这种缓存型数据库，每次请求里面携带ip通过查看ip是否在已经存在的库里面就可以判断当前请求是否是新用户了，(这种情况下，同一ip例如网吧学校这种多人的电脑都会是一个ip所以只会算一个人。这种特殊情况不能准确)</p>
</blockquote>
<blockquote>
<p>第二种，当用户访问网页时，为起本地生成一个24小时cookies，通过判断本地有无cookie来确定是否是新用户，每次请求的时候携带这个身份是否新用户即可，这种方法实现比较简单，同时由于自己的网站也不会也太多访问量所以打算本次就用这种方法</p>
</blockquote>
<ul>
<li>实现的思路有很多，不应该仅仅是这两种，只是因为当前我得需求还很简单，后面扩展功能的时候我们再来补充……</li>
</ul>
</li>
<li><p>第二点如何辨别不同用户，网站要接入，需要辨别不用网站身份，不同网站的唯一身份就用域名来确认即可，域名即是代表自己身份的唯一标识，有了思路，就可以着手了。</p>
</li>
</ul>
<h4 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h4><ul>
<li><p>第一步先封装一个设置cookie和拿cookie的方法用来每次初始化的时候来给客户端设置cookie</p>
<pre><code class="hljs javascript"><span class="hljs-comment">/**</span>
<span class="hljs-comment"> * 设置cookie</span>
<span class="hljs-comment"> * <span class="hljs-doctag">@param </span>name cookie的名称</span>
<span class="hljs-comment"> * <span class="hljs-doctag">@param </span>value cookie的值</span>
<span class="hljs-comment"> * <span class="hljs-doctag">@param </span>day cookie的过期时间</span>
<span class="hljs-comment"> */</span>
<span class="hljs-keyword">var</span> setCookie = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">name, value, day</span>) </span>&#123;
    <span class="hljs-keyword">if</span> (day !== <span class="hljs-number">0</span>) &#123;     <span class="hljs-comment">//当设置的时间等于0时，不设置expires属性，cookie在浏览器关闭后删除</span>
        <span class="hljs-keyword">var</span> expires = day * <span class="hljs-number">24</span> * <span class="hljs-number">60</span> * <span class="hljs-number">60</span> * <span class="hljs-number">1000</span>;
        <span class="hljs-keyword">var</span> date = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(+<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>() + expires);
        <span class="hljs-built_in">document</span>.cookie = name + <span class="hljs-string">"="</span> + <span class="hljs-built_in">escape</span>(value) + <span class="hljs-string">";expires="</span> + date.toUTCString();
    &#125; <span class="hljs-keyword">else</span> &#123;
        <span class="hljs-built_in">document</span>.cookie = name + <span class="hljs-string">"="</span> + <span class="hljs-built_in">escape</span>(value);
    &#125;
&#125;;</code></pre>

<pre><code class="hljs javascript"><span class="hljs-comment">/**</span>
<span class="hljs-comment"> * 获取对应名称的cookie</span>
<span class="hljs-comment"> * <span class="hljs-doctag">@param </span>name cookie的名称</span>
<span class="hljs-comment"> * <span class="hljs-doctag">@returns <span class="hljs-type">&#123;null&#125;</span> </span>不存在时，返回null</span>
<span class="hljs-comment"> */</span>
<span class="hljs-keyword">var</span> getCookie = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">name</span>) </span>&#123;
    <span class="hljs-keyword">var</span> arr;
    <span class="hljs-keyword">var</span> reg = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">"(^| )"</span> + name + <span class="hljs-string">"=([^;]*)(;|$)"</span>);
    <span class="hljs-keyword">if</span> (arr = <span class="hljs-built_in">document</span>.cookie.match(reg))
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">unescape</span>(arr[<span class="hljs-number">2</span>]);
    <span class="hljs-keyword">else</span>
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
&#125;;</code></pre>
</li>
<li><p>封装完cookie的存取之后我们首先要拿到的就是客户端身份标识，在这里我们需要的是域名，我们通过js取到域名</p>
<pre><code class="hljs javascript"><span class="hljs-keyword">var</span> params = &#123;&#125;
<span class="hljs-keyword">if</span> (<span class="hljs-built_in">document</span>) &#123;
    params.domain = <span class="hljs-built_in">document</span>.domain || <span class="hljs-string">''</span>; <span class="hljs-comment">//拿到域名</span>
    params.url = <span class="hljs-built_in">document</span>.URL || <span class="hljs-string">''</span>;    <span class="hljs-comment">//拿到url地址</span>
    params.title = <span class="hljs-built_in">document</span>.title || <span class="hljs-string">''</span>; <span class="hljs-comment">//拿到网站标题</span>
    params.referrer = <span class="hljs-built_in">document</span>.referrer || <span class="hljs-string">''</span>; <span class="hljs-comment">//当前页面和之前页面的链接</span>
&#125;</code></pre>



</li>
</ul>
<ul>
<li><p>我们可以拿到这么多东西，目前只需要用到域名，但是如果埋点还需要监控其他的东西后面的也会用上，暂时全拿到后期扩展埋点功能的时候会用到，下一步进入客户端就是判断当前用户是否存在我们设置的id，如果存在纪为老用户，如果不存在，纪为新用户，这样来区分新老用户：</p>
<pre><code class="hljs javascript"><span class="hljs-keyword">var</span> xiaojiuid = getCookie(<span class="hljs-string">'xiaojiuid'</span>)
<span class="hljs-keyword">var</span> is_new;
<span class="hljs-keyword">if</span> (xiaojiuid) &#123;
    is_new = <span class="hljs-literal">false</span>
&#125; <span class="hljs-keyword">else</span> &#123;
    xiaojiuid = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-number">1099511627776</span> * <span class="hljs-built_in">Math</span>.random());
    setCookie(<span class="hljs-string">'xiaojiuid'</span>, xiaojiuid, <span class="hljs-number">1</span>)
    is_new = <span class="hljs-literal">true</span>
&#125;</code></pre>
</li>
<li><p>然后我们先去获取cookie，如果没有拿到说明我们没有设置，这是第一次进入网站，表示这是一个新用户，那么我们定义一个标量标识当前用户是新用户，反之则不是，如果是新用户，就想cookie设置一个id，这个id是我们生成的一个随机数，并没有实际意义，可以理解为占位的，当然在有的场景下这个cookie应该有服务端设置才能有效，我们目前还不需要，所以这样的操作已经可以实现了，接下来就很简单了，我们只需要用户域名，是否新用户即可。这个时候请求接口就行，我们请求完毕接口之后会拿到返回的pv，uv，只需要把这个数量赋值给需要的地方即可。</p>
<pre><code class="hljs javascript"><span class="hljs-keyword">let</span> options = &#123;
    method: <span class="hljs-string">'post'</span>,<span class="hljs-comment">//post请求</span>
    headers: &#123;
        <span class="hljs-string">'Accept'</span>: <span class="hljs-string">'application/json'</span>,
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
    &#125;,
    body: <span class="hljs-built_in">JSON</span>.stringify(&#123;<span class="hljs-comment">//post请求参数</span>
        domain: params.domain,
        is_new,
    &#125;)
&#125;
fetch(<span class="hljs-string">'https://api.lzwzw.cn/api/statistics/pv'</span>, options).then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> &#123;
    <span class="hljs-keyword">return</span> res.json()
&#125;).then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> &#123;
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'xiaojiu_container_site_pv'</span>).style.display = <span class="hljs-string">''</span>
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'xiaojiu_value_site_pv'</span>).innerText = res.site_pv
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'xiaojiu_container_site_uv'</span>).style.display = <span class="hljs-string">''</span>
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'xiaojiu_value_site_uv'</span>).innerText = res.site_uv
&#125;)
    .catch(<span class="hljs-built_in">console</span>.error)</code></pre>
</li>
<li><p>拿到参数之后 我们这里赋值给了页面dom节点为<code>xiaojiu_container_site_pv</code>的节点，这个呢其实看自己，如果需要用我的就可以按我的这个定义即可，我这里的使用放在了博客的页脚，实际效果是这样</p>
<p><img src="https://api.lzwzw.cn/public/images/%E5%AE%9E%E7%8E%B0%E7%BD%91%E7%AB%99%E6%B5%81%E9%87%8F%E7%BB%9F%E8%AE%A1(%E5%89%8D%E7%AB%AF%E5%9F%8B%E7%82%B9).png" srcset="/img/loading.gif" alt="image-20200625192746273"></p>
<p>至此前端工作已经完成了。</p>
</li>
</ul>
<h4 id="服务端"><a href="#服务端" class="headerlink" title="服务端"></a>服务端</h4><ul>
<li><p>服务端需要做什么呢，第一步就是建表了，这里我用的sql数据库，目前想法很简单，需要的字段第一个身份识别 域名 第二个 pv数量 第三个uv数量</p>
</li>
<li><p>然后服务端这里用到的是nodejs，然后思路也很简单，每次调用这个接口的时候，先查询使用存在当前域名，如果在就是已经存在库里面的网站了，这样就判断拿到的字段is_new是否是新用户，如果是pv,uv都会加一，如果不是新用户，则只需要pv加1即可，同样如果库里没有查询到这个域名，说明网站是第一次使用，则直接插入这条数据，当前网站同时初始化给pv，uv为1即可实现。这里直接上代码：</p>
<pre><code class="hljs javascript">router.post(<span class="hljs-string">'/pv'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; &#123;
    <span class="hljs-built_in">console</span>.log(req.body)
    <span class="hljs-keyword">var</span> reqData = &#123;
        domain: req.body.domain,
        site_pv: <span class="hljs-number">1</span>,
        site_uv: <span class="hljs-number">1</span>,
    &#125;
    <span class="hljs-keyword">let</span> findData = <span class="hljs-keyword">await</span> statistics.findOne(&#123; <span class="hljs-attr">where</span>: &#123; <span class="hljs-attr">domain</span>: req.body.domain &#125; &#125;)
    <span class="hljs-keyword">if</span> (findData) &#123;
        <span class="hljs-keyword">if</span> (!req.body.is_new) &#123;
            findData.site_pv = findData.site_pv + <span class="hljs-number">1</span>;
            saveData = <span class="hljs-keyword">await</span> findData.save();
            <span class="hljs-keyword">if</span> (saveData) &#123;
                res.send(&#123;
                    site_pv: saveData.site_pv,
                    site_uv: saveData.site_uv
                &#125;)
            &#125;
        &#125; <span class="hljs-keyword">else</span> &#123;
            findData.site_pv = findData.site_pv + <span class="hljs-number">1</span>,
                findData.site_uv = findData.site_uv + <span class="hljs-number">1</span>,
                saveData = <span class="hljs-keyword">await</span> findData.save();
            <span class="hljs-keyword">if</span> (saveData) &#123;
                res.send(&#123;
                    site_pv: saveData.site_pv,
                    site_uv: saveData.site_uv
                &#125;)
            &#125;
        &#125;
    &#125; <span class="hljs-keyword">else</span> &#123;
        <span class="hljs-keyword">let</span> user = <span class="hljs-keyword">await</span> statistics.create(reqData)
        <span class="hljs-keyword">if</span> (user) &#123;
            res.send(&#123;
                site_pv: user.site_pv,
                site_uv: user.site_uv
            &#125;)
        &#125;
    &#125;

&#125;)

<span class="hljs-built_in">module</span>.exports = router;</code></pre>

</li>
</ul>
<h4 id="如何在自己的网站使用"><a href="#如何在自己的网站使用" class="headerlink" title="如何在自己的网站使用"></a>如何在自己的网站使用</h4><p>使用起来很简单，只需要两步即可，首先在你的网站引入我的这个js这里我已经为提供了地址，你可以直接引用</p>
<pre><code class="hljs javascript">&lt;script src=<span class="hljs-string">"https://api.lzwzw.cn/public/js/xiaojiu.js"</span>&gt;&lt;<span class="hljs-regexp">/script&gt;</span></code></pre>

<p>第二步就是你想要这个数据展示的位置，只需要在页面放入两个id分别为<code>xiaojiu_container_site_pv</code>和<code>xiaojiu_container_site_uv</code></p>
<p>的dom节点即可，你可以参照我下面这样：</p>
<pre><code class="hljs javascript">&lt;span id=<span class="hljs-string">"xiaojiu_container_site_pv"</span> style=<span class="hljs-string">"display: none;"</span>&gt;本站已经被访问
&lt;span id=<span class="hljs-string">"xiaojiu_value_site_pv"</span> style=<span class="hljs-string">"margin: 0 3px;"</span>&gt;  &lt;<span class="hljs-regexp">/span&gt;次啦&lt;/</span>span&gt;
&lt;span id=<span class="hljs-string">"xiaojiu_container_site_uv"</span> style=<span class="hljs-string">"display: none;"</span>&gt;已经有
&lt;span id=<span class="hljs-string">"xiaojiu_value_site_uv"</span> style=<span class="hljs-string">"margin: 0 3px;"</span>&gt; &lt;<span class="hljs-regexp">/span&gt;个小伙伴来过啦&lt;/</span>span&gt;</code></pre>

<p>当然文字的位置可以随便改，布局样式自己随便调整，只需要id不要错误就行了 ，</p>
<h4 id="案例"><a href="#案例" class="headerlink" title="案例"></a>案例</h4><p>我这里给大家看看我这里的使用，博客使用的hexo搭建，fluid主题，这里我把他放在了底部，如上图，或者在当前博客底部可以看，在文件里的位置就是fotter.ejs文件</p>
<p><img src="https://api.lzwzw.cn/public/images/%E5%AE%9E%E7%8E%B0%E7%BD%91%E7%AB%99%E6%B5%81%E9%87%8F%E7%BB%9F%E8%AE%A1(%E5%89%8D%E7%AB%AF%E5%9F%8B%E7%82%B9)2.png" srcset="/img/loading.gif" alt="image-20200625195008606"></p>
<p>如果你也想使用的话就可以这样操作两步搞定啦。</p>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E4%B8%BB%E9%A2%98%E4%BC%98%E5%8C%96/">主题优化</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/nodeJs/">nodeJs</a>
                    
                      <a class="hover-with-bg" href="/tags/%E5%89%8D%E7%AB%AF%E5%9F%8B%E7%82%B9/">前端埋点</a>
                    
                      <a class="hover-with-bg" href="/tags/%E7%BD%91%E7%AB%99%E6%B5%81%E9%87%8F%E7%BB%9F%E8%AE%A1/">网站流量统计</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/posts/a87jnd.html">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">主题扩展（网站统计量自定义）</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/posts/a93f63ce.html">
                        <span class="hidden-mobile">Node实现随机壁纸API</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script type="text/javascript">
    function loadValine() {
      addScript('https://cdn.staticfile.org/valine/1.4.14/Valine.min.js', function () {
        new Valine({
          el: "#vcomments",
          app_id: "3PpvuTN5QkO4Tih7TqE1W5u8-gzGzoHsz",
          app_key: "2URikzfu2z1jtCXMp3Sy6Oin",
          placeholder: "说点什么",
          path: window.location.pathname,
          avatar: "retro",
          meta: ["nick","mail","link"],
          pageSize: "10",
          lang: "zh-CN",
          highlight: false,
          recordIP: false,
          serverURLs: "",
        });
      });
    }
    createObserver(loadValine, 'vcomments');
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://valine.js.org" target="_blank" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->



<!-- <script>
//去掉畅言下面的跳转连接
  //  声明定时器
var timer = null
//  检查dom是否执行完成
function checkDom() {
    let dom = document.querySelector('.service-wrap-w')
    if(dom) {
      console.log(dom)
         //  执行dom加载完成后的操作
         dom.innerHTML = ''
        //  清除定时器
        if(!timer) {
            clearTimeout(timer)
        }
    } else {
        //  自我调用
        timer = setTimeout(checkDom, 0)
    }
}
//  首次执行
checkDom()
</script> -->
      
    </main>

    
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
    

    
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    

    

    <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <!-- <a  rel="nofollow noopener"><span class="motto">故事若不曲折怎么教人成长</span></a> -->

      <!-- <a rel="nofollow noopener"><span class="motto">xiaojiu</span></a> -->
      <!-- <i class="iconfont icon-love"></i> -->
      <a rel="nofollow noopener">

        <!-- <span class="motto"> 可惜故事太长只有风听我讲</span></a> -->
        
        <span class="motto"> 黄粱一梦、山水万重、人间总相逢</span></a>
        <!-- <span class="motto"> blog</span></a> -->

    </div>
    


    

    
    <div class="xiaojiu">
      <span id="xiaojiu_container_site_pv" style="display: none;">本站已经被访问- <span id="xiaojiu_value_site_pv"
          style="margin: 0 3px;"> </span> -次啦</span>
      <span id="xiaojiu_container_site_uv" style="display: none;">已经有- <span id="xiaojiu_value_site_uv"
          style="margin: 0 3px;"> </span> -个小伙伴来过啦</span>
    </div>


    <div class="date">
      <span id="timeDate">载入天数...</span>
      <span class="times" id="times">载入时分秒...
      </span>
      <img class="time" src="/img/sml.gif" srcset="/img/loading.gif" alt="">
      <script>
        var now = new Date();
        function createtime() {
          var grt = new Date("05/08/2018 00:00:00");//此处修改你的建站时间或者网站上线时间
          now.setTime(now.getTime() + 250);
          days = (now - grt) / 1000 / 60 / 60 / 24;
          dnum = Math.floor(days);
          hours = (now - grt) / 1000 / 60 / 60 - (24 * dnum);
          hnum = Math.floor(hours);
          if (String(hnum).length == 1) {
            hnum = "0" + hnum;
          }
          minutes = (now - grt) / 1000 / 60 - (24 * 60 * dnum) - (60 * hnum);
          mnum = Math.floor(minutes);
          if (String(mnum).length == 1) {
            mnum = "0" + mnum;
          }
          seconds = (now - grt) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
          snum = Math.round(seconds);
          if (String(snum).length == 1) {
            snum = "0" + snum;
          }
          document.getElementById("timeDate").innerHTML = "本站已运行&nbsp" + dnum + "&nbsp天";
          document.getElementById("times").innerHTML = hnum + "&nbsp小时&nbsp" + mnum + "&nbsp分&nbsp" + snum + "&nbsp秒";
        }
        setInterval("createtime()", 250);
      </script>
    </div>
</footer>
<!-- <script src="https://api.lzwzw.cn/public/js/xiaojiu.js"></script> -->
<!-- <script src="/js/xiaojiu.js"></script> -->
<script src="/js/message.js"></script>

<style>
  .xiaojiu {
    margin-top: 14px !important;
    background-image: linear-gradient(135deg, deeppink, dodgerblue);
    font-weight: bold;
    -webkit-background-clip: text;
    -moz-background-clip: text;
    background-clip: text;
    box-decoration-break: clone;
    -webkit-box-decoration-break: clone;
    -moz-box-decoration-break: clone;
    color: transparent;
    position: relative;
  }

  .date {
    background-image: linear-gradient(135deg, deeppink, dodgerblue);
    font-weight: bold;
    -webkit-background-clip: text;
    -moz-background-clip: text;
    background-clip: text;
    box-decoration-break: clone;
    -webkit-box-decoration-break: clone;
    -moz-box-decoration-break: clone;
    color: transparent;
    position: relative;
  }
</style>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>







  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 6,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "实现网站流量统计(前端埋点)&nbsp;",
      ],
      cursorChar: "✨",
      typeSpeed: 80,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
      icon: "❡"
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  



  <script>(function (i, s, o, g, r, a, m) {
      i['DaoVoiceObject'] = r;
      i[r] = i[r] ||
        function () {
          (i[r].q = i[r].q || []).push(arguments);
        };
      i[r].l = 1 * new Date();
      a = s.createElement(o);
      m = s.getElementsByTagName(o)[0];
      a.async = 1;
      a.src = g;
      a.charset = 'utf-8';
      m.parentNode.insertBefore(a, m);
    })(window, document, 'script', ('https:' === document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/2b2e276c.js", 'daovoice');
    daovoice('init', {
      app_id: "2b2e276c",
    });
    daovoice('update');
  </script>










  </div>
  
</body>

</html>
<script>

  // https://uploadbeta.com/api/pictures/random/?key=BingEverydayWallpaperPicture
  // https://source.unsplash.com/random  速度慢  有图还不错
  //https://uploadbeta.com/api/pictures/random/?key=%E6%8E%A8%E5%A5%B3%E9%83%8E 随机女图
  // https://api.jlongyan.cn/api/paper/random
  function checkWallaper() {
    fetch('https://source.unsplash.com/random', {
      method: 'GET',
      mode: 'cors',
    })
      .then(res => {
        setWallaper(res.url)
        localStorage.setItem('blogWallaper',res.url)
        return res.json()
      })
      // .then(res => {
      //   console.log(res);
      //   console.log("%c随机背景图片接口开放%c，随机壁纸api详情见博客,%c小九---!", "color:red", "", "color:orange;font-weight:bold")
      //   setWallaper(res.data.CoverImg)
      //   localStorage.setItem('blogWallaper',res.data.CoverImg)
      // })
      .catch(console.error)
  }

  if(localStorage.getItem('blogWallaper')){
    setWallaper(localStorage.getItem('blogWallaper'))
  }else{
    checkWallaper()
  }

  //设置壁纸
  function setWallaper(url){
    document.getElementById('indexBackground').style.backgroundImage = "url(" + url + ")";
  }

  let timer = null
  //  检查dom是否存在当前页面  监听 
  function watchYiyan() {
    let dom = document.getElementById('yiyan')
    if (dom) {
      fetch('https://v1.hitokoto.cn')
        .then(response => response.json())
        .then(data => {
          dom.innerText = data.hitokoto
        })
        .catch(console.error)
      if (!timer) {
        clearTimeout(timer)
      }
    } else {
      timer = setTimeout(watchYiyan, 0)
    }
  }
  //  首次执行
  watchYiyan()

  setTimeout(() => {
    clearTimeout(timer)
  }, 200);


</script>
